let qiniu = require("qiniu");
const logger = require('../utils/logger')
const totalInfoHandle = require('../utils/totalInfoHandle')

//要上传的空间
let accessKey = 'Jt_e-lkljnoDelPhx0XSqo9906RvGqXzmACCQ_L6';
let secretKey = 'dzDLZ5-qiTj855maNZeB7vHAfaKbQpNbd4HdEhXJ';
let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
let config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z0;
let bucketManager = new qiniu.rs.BucketManager(mac, config);
let bucket = 'wongnai';


function Upload({resUrl, key}, cb) {
  bucketManager.fetch(resUrl, bucket, key, function (err, respBody, respInfo) {
    if (err) {
      cb && cb(err)
    } else {
      if (respInfo.statusCode == 200) {
        console.log('upload sucees', key, resUrl)
        cb && cb(null)
      } else {
        cb && cb(respBody.error)
      }
    }
  });
}

const  UploadRetry = ({resUrl, key}) => {
  let retriesLeft = 5
  let retryTimeout = 10
  return new Promise((resolve, reject) => {
    let cb = err => {
      if(err) {
        if(retriesLeft <= 0) {
          reject(err)
        } else {
          console.log('upload img retry',retriesLeft, 'left', resUrl)
          setTimeout(() => {
            retriesLeft--
            Upload({resUrl, key}, cb)
          }, retryTimeout)
        }
      } else {
        resolve('success')
      }
    }
    Upload({resUrl, key}, cb)
  })
}
/**
 *
 * @param files arry
 * @constructor
 */
function UploadFiles(files, cb = () => {}) {
  if (!Array.isArray(files)) logger.err('params error,files need array')

  files.forEach(v => {
    let {resUrl} = v
    totalInfoHandle.add({
      type: 2,
      url: resUrl
    })
    UploadRetry(v)
      .then(data => {
        totalInfoHandle.addSuccess({
          type:2,
          url: resUrl
        })
      }, err => {
        logger.error('upload img err', err, resUrl)
        totalInfoHandle.addError({
          type:2,
          url: resUrl
        })
      })
  })
}

module.exports = {
  UploadFiles,
  Upload
}